#include <fstream>
#include <iostream>
#include <stdlib.h>
#include "graph.h"

using namespace std;

Graph::Graph()
{
}

AdjacencyList Graph::createVertex(int n)
{
	Vertex vertex(n, 0);
	AdjacencyList adjacencyList;

	adjacencyList.push_back(vertex);

	return adjacencyList;
}

AdjacencyList Graph::addNeighbour(AdjacencyList v, int n, int d)
{
	Vertex vertex(n, d);
	v.push_back(vertex);
	return v;
}

void Graph::addVertex(AdjacencyList adjacencyList)
{
	graph.push_back(adjacencyList);
}

AdjacencyList* Graph::getNeighbourhood(int name)
{
	/*vector<AdjaddcencyList>::iterator it;
	for(it == graph.begin(); it != graph.end(); it++){
		if((*it).front().getName() == name){
			return &(*it);
		}
	}*/
	return &(graph[name - 1]);
}

void Graph::addEdge(int source, int target, int dist)
{
	AdjacencyList adjacencyList;
	Vertex edge(target, dist);

	if(source > (int)graph.size()){
		for(int i = graph.size(); i < source; i++){
			adjacencyList = createVertex(i+1);
			addVertex(adjacencyList);
		}
	}
	graph[source-1].push_back(edge);
}

void Graph::printGraph()
{
	vector<AdjacencyList>::iterator nodo;
	AdjacencyList::iterator it;
	int name;
	cout << "Print Graph" << endl;
	for(nodo = graph.begin(); nodo != graph.end(); nodo++){
		name = (*nodo).front().getName();
		for(it = (*nodo).begin(); it != (*nodo).end(); it++){
			cout << name << " " << (*it).getName() << " " << (*it).getDist() << endl;
		}
	}
	cout << graph.size() << endl;
}



void Graph::loadGraphFromFile(string fileName)
{
	ifstream file;
	string buffer;
	int source, target, dist;
	for(int i = 0; i < graph.size(); i++) graph.pop_back();

	file.open(fileName.c_str());
	//cout << "Loading graph" << endl;
	if(file.is_open()){
		while(!file.eof()){
			file >> buffer;
			if(!buffer.compare("a")){
				file >> buffer;
				source = atoi(buffer.c_str());
				file >> buffer;
				target = atoi(buffer.c_str());
				file >> buffer;
				dist = atoi(buffer.c_str());
				addEdge(source, target, dist);
			}
		}
		file.close();
		//cout << "Graph loaded" << endl;
	} else cout << "Erro on opening file" << endl;
}

void Graph::loadGraph()
{
        string buffer;
        int source, target, dist;
	int edgeNumber, c = 0;	

        //cout << "Loading graph" << endl;
        cin >> buffer;
	while(buffer.compare("p"))cin >> buffer;
        cin >> buffer;
	cin >> buffer;
	cin >> buffer;
	edgeNumber = atoi(buffer.c_str());
        
	while(c < edgeNumber){
        	cin >> buffer;
                if(!buffer.compare("a")){
                	cin >> buffer;
                        source = atoi(buffer.c_str());
                        cin >> buffer;
                        target = atoi(buffer.c_str());
                        cin >> buffer;
                        dist = atoi(buffer.c_str());
                        addEdge(source, target, dist);
                 }
		c++;		
	}
        //cout << "Graph loaded" << endl;
}
	

